package CAS;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicMarkableReference;

/**
 * @program: javase
 * @description: 解决ABA问题
 * @author: luolidong
 * @create: 2021-06-24 22:51
 * @version: 1.0
 */
public class ABA1 {
    private static final String A = "A";
    private static final String B = "B";
    private static final String C = "C";
    private static AtomicMarkableReference<String> reference = new AtomicMarkableReference<>(A, false);

    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {

            if (reference.compareAndSet(A, B, false, true)) {
                System.out.println(reference.isMarked());
                System.out.println("A-->B");
            }
        }).start();
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(reference.isMarked());
            if (reference.compareAndSet(B, A, reference.isMarked(), true)) {
                System.out.println("B-->A");
            }
        }).start();
//        上面两个线程将A->B->A,后面线程不能成功交换
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (reference.compareAndSet(A, C, false, true)) {
                System.out.println("A-->C");
            }
        }).start();

    }
}
